#!/bin/bash

# $1 mount basedir relative to home,e.g. "Music"
# $2 ssh host to look up, also final mountdir
# => mountdir=$HOME/$1/$2
# $3 remote directory to mount
# the rest will be exec'd after mounting is done

me="${0##*/}"
#exec > /tmp/$me.log 2>&1

(( $# < 4 )) && { echo "Please provide mountbase, host, remote dir and command to execute"; exit 1; }

for var in mountbase host remotedir; do
	declare "$var"="$1"
	echo "$var"="$1"
	shift
done

mountdir="$HOME/$mountbase/$host" # will be expanded with name of host

. ~/.config/bash/notify

date

text="mounted on $mountdir with"
text="$(grep "$text" /proc/self/mountstats)"
if [[ "$text" != "" ]]
then
    notify "" "" "" "" "" "~${mountdir#$HOME} already mounted"
else

	# dependency checks
	for dep in sshfs ssh fusermount; do
	    command -V $dep >/dev/null || exit 1
	done

	hostname=''
	port=''
	user=''
	identityfile=''
	serveraliveinterval=''
	identitiesonly=''
	compression=''

	while read option value; do
	    option="${option,,}"
	    case "$option" in
	    hostname|port|user|serveraliveinterval|identitiesonly|identityfile|compression)
	        declare "$option"="$value"
	        echo "$option"="$value"
	    ;;
	    esac
	done <<<"$(ssh -G "$host")"


	sshfs_options="follow_symlinks,ServerAliveInterval=$serveraliveinterval,reconnect,port=$port,IdentitiesOnly=$identitiesonly,IdentityFile=$identityfile,Compression=$compression"

	mkdir -p "$mountdir" || exit 1
	location="${user}@$hostname:$remotedir"
	if sshfs -C -o "$sshfs_options" "$location" "$mountdir"
	then
		notify "" "" "" "" "" "Mounted $location on ~${mountdir#$HOME}"
	else
	    notify "" "icon-lock-warning" "" "" "" "Failed: mounting $location"
	    fusermount -u -z "$mountdir"
	fi
fi

"$@"

grep "mounted on $mountdir with" /proc/self/mountstats && fusermount -u "$mountdir"
sleep 10
grep "mounted on $mountdir with" /proc/self/mountstats && fusermount -u -z "$mountdir"

exit 0
